package com.material.vtool.interceptor;

import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.exception.ServiceException;
import com.material.vtool.service.UserInfoService;
import com.material.vtool.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserReqInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String userId = request.getHeader("userId");
        String userSessionId = request.getHeader("userSessionId");
        log.info("[requestURI] = " + requestURI + " [userId] = " + userId + " [userSessionId] = " + userSessionId);

        // 放行的路径
        if (!requestURI.contains("/wechat") && !requestURI.contains("/materialShareLink")) {
            if (StringUtils.isBlank(userId) || !StringUtils.isNumeric(userId.trim())) {
                throw new ServiceException("用户未登录", ReturnCode.NOT_LOGIN);
            }

            String openId = null;
            if (StringUtils.isNotBlank(userId) && StringUtils.isNumeric(userId)) {
                openId = userInfoService.getUserOpenId(Integer.parseInt(userId));
                boolean verifyResult = ToolUtil.verify(userId + openId, userSessionId);
                if (StringUtils.isBlank(openId) || StringUtils.isBlank(userSessionId) || !verifyResult) {
                    throw new ServiceException("用户未登录", ReturnCode.NOT_LOGIN);  //调试时屏蔽
                }
            }
        }
        return true;
    }
}
